/*
 * Copyright (c) 2021. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package com.kason.framework.protocol.dubbo;

import com.kason.framework.Invocation;
import com.kason.framework.Remote;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 卢清波
 * @date 2021/2/20 11:05
 */
public class NettyClient
{
    private static ExecutorService executorService = Executors.newCachedThreadPool();

    static Bootstrap b = null ;
    static NettyClientHandler client = null ;

    public void start(Remote remote) throws InterruptedException
    {
        try
        {
            client = new NettyClientHandler();
            EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
            b = new Bootstrap();
            b.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY,Boolean.TRUE)
                    .handler(new ChannelInitializer<NioSocketChannel>()
                    {
                        @Override
                        protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception
                        {
                            ChannelPipeline pipeline = nioSocketChannel.pipeline();
                            pipeline.addLast("decoder",new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
                            pipeline.addLast("encoder",new ObjectEncoder());
                            pipeline.addLast(client);
                        }
                    });
            b.connect(remote.getHostname(), remote.getPort()).sync();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public String send(Remote remote, Invocation invocation) throws Exception{
        if(b==null)
        {
            start(remote);
        }
        client.setInvocation(invocation);
        try
        {
            Object o = executorService.submit(client).get();
            return (String) o;
        }
        catch (Exception ex)
        {
           ex.printStackTrace();
        }
        return null ;

    }








}
